import psutil,collections,os,sys,time,datetime

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from collections import namedtuple


def get_ecs_cpu_and_memory():
    data = psutil.virtual_memory()
    total = data.total  # 总内存,单位为byte
    total = round(total / 1024 / 1024 / 1024, 2)  # 转换成GB
    free = data.available  # 可用内存
    free = round(free / 1024 / 1024 / 1024, 2)  # 转换成GB
    memory = "内存使用:%0.2f" % (int(round(data.percent))) + "%"  # 内存使用情况
    cpu = "CPU占用:%0.2f" % psutil.cpu_percent(interval=1) + "%"  # CPU占用情况
    return cpu, memory, total, free


def sysCentos():
    # print('-----------------------------系统基本信息---------------------------------------')
    # 当前时间
    now_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
    # print(now_time)
    # 系统启动时间
    # print(u"系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"))
    # 系统用户
    users_count = len(psutil.users())
    users_list = ",".join([u.name for u in psutil.users()])
    # print(u"当前有%s个用户，分别是 %s" % (users_count, users_list))
    centosDate = '系统启动时间:' + str(datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")) +'\n' + "当前有" + str(users_count) +"个用户:"+ users_list
    return  centosDate

def systemCpu():
    # print('-----------------------------C-P-U--------------------------------------------')
    cpu, memory, total, free = get_ecs_cpu_and_memory()
    # print(cpu)
    # print(memory)
    # 查看cpu物理个数的信息
    # print(u"物理CPU个数: %s" % psutil.cpu_count(logical=False))
    # print(u"CPU核心总数: %s" % psutil.cpu_count())
    # CPU的使用率
    cpu = (str(psutil.cpu_percent(1))) + '%'
    if psutil.cpu_percent(1) > 5:
        ret = mail("cpu使用率过高:", "cpu使用率过高")
    #     if ret:
    #         print("cpu:邮件发送成功")
    #     else:
    #         print("cpu:邮件发送失败")
    # print(u"cup使用率: %s" % cpu)
    return '物理CPU个数:' + str(psutil.cpu_count(logical=False)) + "\n" +"CPU核心总数:" + str(psutil.cpu_count()) + '\n' + "cpu使用率：" + cpu

def systemMemory():
    # print('-----------------------------内存---------------------------------------------')
    free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))
    total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))
    memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
    # print(u"物理内存： %s G" % total)
    # print(u"剩余物理内存： %s G" % free)
    # print(u"物理内存使用率： %s %%" % int(memory * 100))
    temp = round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2)
    # print(temp)
    if temp < 0.25:
        a=("需要增加内存：剩余内存" + str(free)+"\n" +"物理内存使用率:"+str(memory))
        ret = mail("内存不足10%",a + sysCentos())
        if ret:
            print("cpu:邮件发送成功")
        else:
            print("cpu:邮件发送失败")

    return "物理内存："+ total +"\n" +"剩余物理内存：" + free+"\n"  + "物理内存使用率：" + str(memory * 100)+"\n"

def systemNetwork():
    # print('-----------------------------网络信息---------------------------------------')
    # 网卡，可以得到网卡属性，连接数，当前流量等信息
    net = psutil.net_io_counters()
    bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
    bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
    # print(u"网卡接收流量 %s 网卡发送流量 %s" % (bytes_rcvd, bytes_sent))
    return "网卡接收流量" + bytes_rcvd +"\n" +"网卡发送流量" + bytes_sent+"\n"

def systemDisk():
    # print('-----------------------------磁盘信息---------------------------------------')
    io = psutil.disk_partitions()
    # print("系统磁盘信息：" + str(io))
    li =[]
    for i in io:

        try:
            o = psutil.disk_usage(i.device)
            if int(o.total / (1024.0 * 1024.0 * 1024.0)) == 0:
                continue
            ioo = psutil.disk_io_counters()
            # print(ioo)
        except Exception as e:
            pass
        # print("%s盘总容量：" % i.device + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
        # print("已用容量：" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
        # print("可用容量：" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")
        a = ("盘总容量: " + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
        d = ("盘路径：" + i.device + "\n")
        b = ("已用容量：" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
        c  = ("可用容量：" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")

        if int(o.free / (1024.0 * 1024.0 * 1024.0)) > 20:
            ret = mail("需要增加硬盘:"  + sysCentos() + i.device +"\n" +a +"\n"+b+"\n"+ c, "硬盘控件不足10%")
            # if ret:
            #     print("磁盘：邮件发送成功")
            # else:
            #     print("磁盘：邮件发送失败")
        li.append(a)
        li.append(b)
        li.append(c)



    return li
#         传一个内容，一个主题

my_sender = '381224567@qq.com'  # 发件人邮箱账号
my_pass = 'xysngillmmfhcajcdt'  # 发件人邮箱密码
my_user = '381224567@qq.com'  # 收件人邮箱账号，我这边发送给自己


def mail(str,str1):
    ret = True
    try:
        msg = MIMEText(str1, 'plain', 'utf-8')
        msg['From'] = formataddr(["82.157.25.239", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        msg['To'] = formataddr(["FK", my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        msg['Subject'] = str  # 邮件的主题，也可以说是标题

        server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是25
        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(my_sender, [my_user, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
    except Exception:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False
        ret = False
    return ret
if __name__ == "__main__":
    while True:
        sysCentos()

        systemCpu()

        systemMemory()

        systemNetwork()

        systemDisk()


        time.sleep(7)
    # email("需要增加设备","内存不够预警")











